import pymysql


class DButil:
    conn = None

    # 封装数据库连接方法
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                                   database="ihrm", charset="utf8")
        return cls.conn

    # 封装数据库关闭方法
    @classmethod
    def __closure_db(cls):
        cls.conn.close()

    # 数据库查询方法
    @classmethod
    def Inquire_db(cls, sql):
        cursor = None
        result = None
        try:
            # 创建数据库连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句,返回结果
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as err:
            print("查询数据库错误:", err)
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__closure_db()
            return result

    # 数据库增删改方法
    @classmethod
    def uid_db(cls, sql):
        # 定义变量
        cursor = None
        try:
            # 创建数据库连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句,打印影响行数
            cursor.execute(sql)
            affted_rows = cls.conn.affected_rows()
            print('影响行数:', affted_rows)
            # 事务提交,回滚
            cls.conn.commit()
        except Exception as err:
            print("增删改操作失败:", err)
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__closure_db()


if __name__ == '__main__':
    # print(DButil.Inquire_db("select * from t_book"))
    # DButil.uid_db("UPDATE t_book set `read` = `read` +1 WHERE id =1; ")
    print(DButil.Inquire_db("select is_delete from bs_user where mobile = '15137205059'"))

